package reptile

import (
	"io/ioutil"
	"net/http"
	"regexp"
	"robot/study/LiveRobot/sdk/zlog"
	"strconv"
	"strings"
)

/**
Spider
*/
var Sqa = "aaaa"

type Spider struct {
	Str string
}

func (spi *Spider) Work() ([]string, []string) {

	//伪造浏览器请求
	client := http.Client{}
	req, _ := http.NewRequest("GET", spi.Str, nil)
	req.Header.Set("Cookie", "_uuid=5C9E9094-8A56-20EF-C10F-8FBE58390BFB22000infoc; buvid3=B2672018-2698-4BDC-AE58-564EC14C30AE148806infoc; b_nut=1629256422; blackside_state=1; rpdid=|(J~|umklY~l0J'uYkmklYJmm; CURRENT_BLACKGAP=1; CURRENT_QUALITY=0; sid=69a67a9u; fingerprint=8393a40defe12176df42025a6970a678; buvid_fp=B2672018-2698-4BDC-AE58-564EC14C30AE148806infoc; buvid_fp_plain=7FF5D848-74C4-0E21-4F47-F867E5EB1C6121420infoc; CURRENT_FNVAL=976; innersign=0; bsource=search_baidu")
	req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38")
	req.Header.Set("Referer", "https://www.bilibili.com/")
	resp, err2 := client.Do(req)
	if err2 != nil {
		zlog.Error("请求失败")
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		zlog.Error(`read err`)
		return nil, nil
	}
	bodys := Unico(string(body))
	//fmt.Println(bodys)
	return spi.dealBody(bodys)
}

func (spi *Spider) dealBody(body string) ([]string, []string) {
	switch spi.Str {
	//case `http://www.baidu.com/`:
	//	pre, _ := regexp.Compile(`(hot)(.)*"`)
	//	body = pre.FindString(body)
	//	//suf,_:=regexp.Compile(`ul$`)
	//	//body=suf.FindString(body)
	//	fmt.Println(body)
	//	return body
	case `https://www.bilibili.com/v/popular/all?spm_id_from=333.851.b_7072696d61727950616765546162.3`:
		pre, _ := regexp.Compile(`(short_link":")(https?)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]`)
		res := pre.FindAllString(body, 3)
		pre2, _ := regexp.Compile(`(title":").*?"`)
		resTitle := pre2.FindAllString(body, 3)
		for i := 0; i < len(res); i++ {
			res[i] = res[i][13:]
		}
		for i := 0; i < len(resTitle); i++ {
			resTitle[i] = resTitle[i][8 : len(resTitle[i])-1]
		}
		zlog.Info(resTitle)
		zlog.Info(res)
		return resTitle, res
	}
	return nil, nil
}

func Unico(s string) string {
	str, err := strconv.Unquote(strings.Replace(strconv.Quote(s), `\\u`, `\u`, -1))
	if err != nil {
		zlog.Error("解码失败")
	}
	return str
}
